package cn.chrilwe.zk.starter.config;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 
 * @author chrilwe
 * 2020-7-26
 */
@Configuration
public class ZkLockConfiguration {

	public class ZkLock implements Lock {
		
		protected ZooKeeper client;
		
		public ZkLock(ZooKeeper client) {
			this.client = client;
		}

		@Override
		public void lock() {
			
		}

		@Override
		public void lockInterruptibly() throws InterruptedException {
			// TODO Auto-generated method stub
			
		}

		@Override
		public Condition newCondition() {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public boolean tryLock() {
			try {
				String path = client.create(LOCK, "".getBytes(), null, CreateMode.EPHEMERAL_SEQUENTIAL);
				if(StringUtils.isEmpty(path)) {
					return false;
				}
				
				Integer lockNum = Integer.parseInt(path.substring(0, LOCK.length()-1));
				String beforeLockPath = LOCK + lockNum;
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			} 
			return false;
		}

		@Override
		public boolean tryLock(long arg0, TimeUnit arg1) throws InterruptedException {
			// TODO Auto-generated method stub
			return false;
		}

		@Override
		public void unlock() {
			// TODO Auto-generated method stub
			
		}
		
	}
	
	
	@Autowired
	protected ZooKeeper zooKeeper;
	
	protected static String LOCK = "/lock";
	
	@Bean
	public ZkLock zkLock() {
		
		return new ZkLock(zooKeeper);
	}
	
}
